package fr.inria.arles.temperatureManagement.utility;

import fr.inria.arles.temperatureManagement.exceptions.TimeoutException;
import org.cybergarage.upnp.ControlPoint;
import org.cybergarage.upnp.Device;
import static fr.inria.arles.temperatureManagement.Constants.*;

/**
 * Class providinng UPnP Device search facility.
 * @author ajay chhatwal
 */
public class DeviceFinder {

    /**
     * Searches for the named UPnP device till it is found or timeout occurs.
     * The timeout is defined in the Constants
     * 
     * @param cp The control point used for the search (should have be started)
     * @param deviceName The friendly name of the device being searched for.
     *
     * @return The device searched for.
     *
     * @throws TimeoutException if timeout occurs
     */
    public static Device searchForDevice(ControlPoint cp, String deviceName)
            throws TimeoutException {
        long startTime = System.currentTimeMillis();
        System.out.println("Searching for Device: " + deviceName);
        while (true) {
            if (System.currentTimeMillis() - startTime > NETWORK_TIMEOUT_MILLIS) {
                System.out.println("Device: " + deviceName + " not found.");
                System.out.println("Timeout:" + NETWORK_TIMEOUT_MILLIS
                        + " milisec");
                throw new TimeoutException();
            }
            cp.search();
            Device dev = cp.getDevice(deviceName);
            if (dev != null) {
                System.out.println("Device " + deviceName + " found");
                return dev;
            }
        }
    }
}
